home *** CD-ROM | disk | FTP | other *** search
- Path: news1.cris.com!voyager!Crawford
- From: Crawford@voyager.cris.com (CRAWFORD)
- Newsgroups: comp.lang.c
- Subject: Re: returning a string from a function
- Date: 12 Jan 1996 09:41:50 -0500
- Organization: Concentric Internet Services
- Message-ID: <Crawford.821457029@voyager>
- References: <4d4uh8$q46@mailhost.mwmicro.com>
- Reply-To: crawford@iac.net
- NNTP-Posting-Host: voyager-fddi.cris.com
-
- aschlies@citynet.net (Tony Schliesser) writes:
- >char function_name(char in_string[80])
- >{
- > char value[80];
- > ...value takes on part of the value of the last 10 characters
- > of in_string.
- > return(value);
- >}
- >jWhen this function is done, it only returns the first character. I
- >"watched" the program execution and it shows that value indeed has the
- >last 10 characters. Any clues as to why the calling routine only gets
- >the one character??
-
- There are _lots_ of problems with the function definition
- you've given us:
-
- 1. You're declaring the function to return a character, and
- your argument for return is a character pointer.
- 2. You're attempting to return a pointer to an automatic
- variable.
-
- A more correct version is:
-
- char *function_name (char in_string[])
- {
- static char value[80];
-
- /* copy the characters */
-
- return value;
- }
-
- Since you want to return more than one character, the function
- has to return a pointer to a string. You have to declare value as
- static because otherwise it's allocated on the stack and will probably
- be corrupted -- or you'll modify its contents and corrupt the stack
- yourself.
-
- --
- Creature of the wheel, master of the internal combustion engine.
-
- Robert Crawford crawford@iac.net
- http://www.iac.net/~crawford
-